package nd.android.am;

import nd.android.am.Adapter.Account;
import nd.android.am.bean.AccountBean;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class AccountEditor extends Activity {
    private static final String TAG = "AccountEditor";
    private static final int MENU_ITEM_DELETE = Menu.FIRST;
    private static final int MENU_ITEM_RETURN = Menu.FIRST + 1;

    private AccountBean original;
    private Uri uri ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account_editor);
        
        Intent intent = getIntent();
        String action = intent.getAction();
        int resetLabel = R.string.button_continue;
        uri = intent.getData();
        if (Intent.ACTION_EDIT.equals(action)) {
        	
            resetLabel = R.string.button_reset;
            Cursor cursor = managedQuery(uri, Account.PROJECTION,
            		Account.STATUS + "=0", null, Account.DEFAULT_SORT_ORDER);
            original = Account.getAccount(cursor);
            cursor.close();
        } else if (Intent.ACTION_INSERT.equals(action)) {

        } else {
            Log.e(TAG, "Unknown action, exiting");
            finish();
            return;
        }
        reset(original);

        Button resetButton = (Button)findViewById(R.id.reset); 
        resetButton.setText(resetLabel);
        resetButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	if(original == null){
            		save();
            	}
            	reset(original);
            }
        });

        
        Button saveButton = (Button) findViewById(R.id.save);
        saveButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	save();
            	finish();
            	Intent intent = new Intent("android.intent.action.Refresh");
            	setResult(RESULT_OK, intent);
            }
        });
        
        ((Button)findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
		        setResult(RESULT_CANCELED);
				finish();
			}});
    }
    
    private void reset(AccountBean original) {
    	if(original == null)
    		original = new AccountBean();
        ((EditText)findViewById(R.id.occur_edit)).setText(original.getOccurDate());
        ((EditText)findViewById(R.id.purpose_edit)).setText(original.getPurpose());
        ((EditText)findViewById(R.id.amout_edit)).setText(this.original == null ? "" : String.valueOf(original.getAmount()));
        ((EditText)findViewById(R.id.payer_edit)).setText(original.getPayer());
        ((EditText)findViewById(R.id.users_edit)).setText(original.getUsers());
        ((EditText)findViewById(R.id.desc_edit)).setText(original.getDesc());
    }
    
    private void save() {
    	String occurDate = ((EditText)findViewById(R.id.occur_edit)).getText().toString();
    	String purpose = ((EditText)findViewById(R.id.purpose_edit)).getText().toString();
    	double amount = Double.valueOf(((EditText)findViewById(R.id.amout_edit)).getText().toString());
    	String payer = ((EditText)findViewById(R.id.payer_edit)).getText().toString();
    	String users = ((EditText)findViewById(R.id.users_edit)).getText().toString();
    	String desc = ((EditText)findViewById(R.id.desc_edit)).getText().toString();
    	valid();
    	ContentValues v = new ContentValues();
    	v.put(Account.OCCUR_DATE, occurDate);
    	v.put(Account.PURPOSE, purpose);
    	v.put(Account.AMOUNT, (long)(amount * 100));
    	v.put(Account.PAYER, payer);
    	v.put(Account.USERS, users);
    	v.put(Account.DESC, desc);
    	v.put(Account.UPDATE_DATE, System.currentTimeMillis());
    	if(original == null)
    		getContentResolver().insert(uri, v);
    	else
    		getContentResolver().update(uri, v, null, null);
    }
    
    private void delete() {
    	getContentResolver().delete(uri, null, null);
    }
    
    private String valid() {
    	//TODO 校验
    	return null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

		menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_delete)
				.setShortcut('1', 'd').setIcon(android.R.drawable.ic_menu_delete);
		menu.add(0, MENU_ITEM_RETURN, 0, R.string.menu_return)
				.setShortcut('2', 'r').setIcon(android.R.drawable.ic_menu_share);
        
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		boolean b = original != null;
		menu.findItem(MENU_ITEM_DELETE).setEnabled(b);
		return true;
	}
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ITEM_DELETE:
            showDialog(DIALOG_YES_NO_MESSAGE);
            return true;
        case MENU_ITEM_RETURN:
        	finish();
        	return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private static final int DIALOG_YES_NO_MESSAGE = 1;
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_YES_NO_MESSAGE:
            return new AlertDialog.Builder(this)
                .setTitle(R.string.confirm_title).setMessage(R.string.confirm_delete_message)
                .setPositiveButton(R.string.confirm_OK, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	delete();
                    	finish();
                    }
                })
                .setNegativeButton(R.string.confirm_Cancel, null)
                .create();
        }
        return null;
    }

    public void setObject(int s) {
    	Log.i("invoke", "setObject");
    }
    public String invokeObject() {
    	Log.i("invoke", "invokeObject");
    	return "invokeObject success";
    }
    public void setCharSequence(CharSequence s) {
    	Log.i("invoke", "setCharSequence(" + s);
    }
    public void setString(String s) {
    	Log.i("invoke", "setString(" + s);
    }
}
